<template>
  <div class="api-test-container">
    <h1>API测试页面</h1>
    
    <!-- 用户管理API测试 -->
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <h2>用户管理API测试</h2>
        </div>
      </template>
      
      <!-- 用户注册 -->
      <div class="api-section">
        <h3>1.1 用户注册</h3>
        <el-form :model="registerForm" label-width="100px">
          <el-form-item label="用户名">
            <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="registerForm.role" placeholder="请选择角色">
              <el-option label="客户" value="customer"></el-option>
              <el-option label="采购员" value="purchaser"></el-option>
              <el-option label="销售员" value="salesman"></el-option>
              <el-option label="配送员" value="deliveryman"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="registerForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="registerForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleRegister">注册</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ registerResult }}</pre>
        </div>
      </div>
      
      <!-- 用户登录 -->
      <div class="api-section">
        <h3>1.2 用户登录</h3>
        <el-form :model="loginForm" label-width="100px">
          <el-form-item label="用户名">
            <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin">登录</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ loginResult }}</pre>
        </div>
      </div>
      
      <!-- 获取用户信息 -->
      <div class="api-section">
        <h3>1.3 获取用户信息</h3>
        <el-button type="primary" @click="handleGetUserInfo">获取用户信息</el-button>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ userInfoResult }}</pre>
        </div>
      </div>
      
      <!-- 更新用户信息 -->
      <div class="api-section">
        <h3>1.4 更新用户信息</h3>
        <el-form :model="updateProfileForm" label-width="100px">
          <el-form-item label="邮箱">
            <el-input v-model="updateProfileForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="updateProfileForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleUpdateProfile">更新</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ updateProfileResult }}</pre>
        </div>
      </div>
      
      <!-- 修改密码 -->
      <div class="api-section">
        <h3>1.5 修改密码</h3>
        <el-form :model="changePasswordForm" label-width="100px">
          <el-form-item label="旧密码">
            <el-input v-model="changePasswordForm.old_password" type="password" placeholder="请输入旧密码" show-password></el-input>
          </el-form-item>
          <el-form-item label="新密码">
            <el-input v-model="changePasswordForm.new_password" type="password" placeholder="请输入新密码" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleChangePassword">修改</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ changePasswordResult }}</pre>
        </div>
      </div>
      
      <!-- 获取用户列表 (管理员) -->
      <div class="api-section">
        <h3>1.6 获取用户列表 (管理员)</h3>
        <el-form :model="getUsersForm" label-width="100px">
          <el-form-item label="角色">
            <el-select v-model="getUsersForm.role" placeholder="请选择角色" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="管理员" value="admin"></el-option>
              <el-option label="客户" value="customer"></el-option>
              <el-option label="采购员" value="purchaser"></el-option>
              <el-option label="销售员" value="salesman"></el-option>
              <el-option label="配送员" value="deliveryman"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="页码">
            <el-input-number v-model="getUsersForm.page" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="每页数量">
            <el-input-number v-model="getUsersForm.limit" :min="1" :max="50"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleGetUsers">获取</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ getUsersResult }}</pre>
        </div>
      </div>
      
      <!-- 修改用户角色 (管理员) -->
      <div class="api-section">
        <h3>1.7 修改用户角色 (管理员)</h3>
        <el-form :model="changeRoleForm" label-width="100px">
          <el-form-item label="用户ID">
            <el-input v-model="changeRoleForm.id" placeholder="请输入用户ID"></el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="changeRoleForm.role" placeholder="请选择角色">
              <el-option label="管理员" value="admin"></el-option>
              <el-option label="客户" value="customer"></el-option>
              <el-option label="采购员" value="purchaser"></el-option>
              <el-option label="销售员" value="salesman"></el-option>
              <el-option label="配送员" value="deliveryman"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleChangeRole">修改</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ changeRoleResult }}</pre>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'

// 用户注册
const registerForm = reactive({
  username: '',
  password: '',
  role: 'customer',
  email: '',
  phone: ''
})
const registerResult = ref('')

const handleRegister = async () => {
  try {
    const response = await axios.post('/api/users/register/', registerForm) // 修改后的请求 URL
    registerResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('注册成功')
  } catch (error) {
    registerResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
    ElMessage.error('注册失败')
  }
}

// 用户登录
const loginForm = reactive({
  username: '',
  password: ''
})
const loginResult = ref('')

const handleLogin = async () => {
  try {
    const response = await axios.post('/api/users/login/', loginForm) // 修改此行
    loginResult.value = JSON.stringify(response.data)
    // 保存 access_token 到 localStorage
    if (response.data && response.data.access) {
      localStorage.setItem('access_token', response.data.access)
      // 可选：同时保存 refresh_token
      if (response.data.refresh) {
        localStorage.setItem('refresh_token', response.data.refresh)
      }
      console.log('Login successful, token saved:', response.data.access)
    } else {
      console.error('Login successful, but access token not found in response:', response.data)
    }
  } catch (error) {
    loginResult.value = `Login failed: ${error.response ? JSON.stringify(error.response.data) : error.message}`
    console.error('Login error:', error.response ? error.response.data : error)
  }
}

// 获取用户信息
const userInfoResult = ref('')

// 获取用户信息函数
const handleGetUserInfo = async () => {
  try {
    const token = getToken()
    console.log('Token from getToken():', token); // 在这里打印token
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    const response = await axios.get('/api/users/profile/', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    userInfoResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('获取成功')
  } catch (error) {
    userInfoResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
    ElMessage.error('获取失败')
  }
}

// 更新用户信息
const updateProfileForm = reactive({
  email: '',
  phone: ''
})
const updateProfileResult = ref('')

// 更新用户信息函数
const handleUpdateProfile = async () => {
  try {
    const response = await axios.put('/api/users/me/update/', updateProfileForm, { // 修改此处的 URL
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    });
    updateProfileResult.value = JSON.stringify(response.data, null, 2); // 将结果保存到 updateProfileResult
    ElMessage.success('用户信息更新成功');
    // 可选：更新成功后，重新获取用户信息以显示最新数据
    await handleGetUserInfo(); 
  } catch (error) {
    updateProfileResult.value = JSON.stringify(error.response?.data || error.message, null, 2);
    console.error('更新用户信息失败:', error.response ? error.response.data : error.message);
    ElMessage.error('更新用户信息失败: ' + (error.response && error.response.data && error.response.data.detail ? error.response.data.detail : error.message));
  }
};

// 修改密码
const changePasswordForm = reactive({
  old_password: '',
  new_password: ''
})
const changePasswordResult = ref('')

// 修改密码函数
const handleChangePassword = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    const response = await axios.post('/api/users/change-password/', changePasswordForm, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    changePasswordResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('修改成功')
  } catch (error) {
    changePasswordResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
    ElMessage.error('修改失败')
  }
}

// 获取用户列表 (管理员)
const getUsersForm = reactive({
  role: '',
  page: 1,
  limit: 10
})
const getUsersResult = ref('')

const handleGetUsers = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    const params = {}
    if (getUsersForm.role) params.role = getUsersForm.role
    if (getUsersForm.page) params.page = getUsersForm.page
    if (getUsersForm.limit) params.limit = getUsersForm.limit
    
    // 修改这里的 URL
    const response = await axios.get('/api/users/all/', { // <--- 修改这里
      params,
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    getUsersResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('获取成功')
  } catch (error) {
    getUsersResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
    ElMessage.error('获取失败: ' + (error.response?.data?.detail || error.message)) // 改进错误提示
  }
}

// 修改用户角色 (管理员)
const changeRoleForm = reactive({
  id: '',
  role: ''
})
const changeRoleResult = ref('')

const handleChangeRole = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    const response = await axios.put(`/api/users/${changeRoleForm.id}/update-role/`, { // 修改此处的 URL
      role: changeRoleForm.role
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    changeRoleResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('修改成功')
  } catch (error) {
    changeRoleResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
    ElMessage.error('修改失败')
  }
}
</script>

<style scoped>
.api-test-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.api-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.api-section:last-child {
  border-bottom: none;
}

.api-result {
  margin-top: 15px;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
}
</style>